package com.ruoyi.web.controller.webContent;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.http.HttpClient;
import com.ruoyi.common.utils.http.HttpsClientUtil;
import com.ruoyi.web.controller.tool.ApplicationContextUtil;
import com.ruoyi.webContent.domain.PlCalculateResult;
import com.ruoyi.webContent.domain.PlMatchType;
import com.ruoyi.webContent.domain.PlTeam;
import com.ruoyi.webContent.service.IPlCalculateResultService;
import com.ruoyi.webContent.service.IPlMatchTypeService;
import com.ruoyi.webContent.service.IPlTeamService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.webContent.domain.ZhgsWebContent;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.annotation.PostConstruct;

/**
 * 动态页面数据功能Controller
 *
 * @author ruoyi
 * @date 2020-05-07
 */
@Controller
@RequestMapping("/webContent/content")
public class ZhgsWebContentController extends BaseController {
    private String prefix = "webContent/content";

//    @Autowired
//    private IPlTeamService plTeamService;
//    @Autowired
//    private IPlTeamService plTeamService;

    @RequiresPermissions("webContent:content:view")
    @GetMapping()
    public String content() {
        return prefix + "/content";
    }

    //存储所有比赛定时更新
    List<Map> matchCode = null;
    //获取所有比赛
    static JSONArray lh_allMatch = new JSONArray();
    static JSONArray ldj_allMatch = new JSONArray();
    static JSONArray yb_allMatch = new JSONArray();
    //获取所有比赛详细信息 比赛id:比赛详情
    static Map<String,JSONObject> ldj_match_contents = null;
    static Map<String,JSONObject> yb_match_contents = null;
    static Map<String,JSONObject> lh_match_contents = null;
    //组装比赛对应 host_code:match_id
    static List<Map<String,String>> yb_ldj_code = null;
    static List<Map<String,String>> yb_lh_code = null;
    static List<Map<String,String>> ldj_lh_code = null;
    //获取所有队伍
    static List<PlTeam> plTeams = null;
    //所有赔率类型
    static List<PlMatchType> plMatchTypes = null;

    //所有要比对的赔率类型
//    static List<Map> plLxList = null;
    //设定更新时间，秒数
    Long refshTime = 600L;
    //上次更新时间
    Long lastrefshTime = 0L;
    //雷火token
    String lh_token = "Token 9278cadf62902610a21cfecfc60b8eeb2c830e93";

    /**
     * 查询动态页面数据功能列表
     */
//    @RequiresPermissions("webContent:content:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list() {
        setTeam();
//        get_lh_allMatch("英雄联盟");
//        startPage();
//        List<ZhgsWebContent> list = zhgsWebContentService.selectZhgsWebContentList(zhgsWebContent);
//        return getDataTable(list);
        return null;
    }
    //设置所有的需要采集的赔率类型
    @PostConstruct
    public List<Map> getPlLxList() {
        //总胜利
        Map plLxMap1 = new HashMap();
        plLxMap1.put("matchType","Winner_final");//赔率名称
        plLxMap1.put("matchType_ch","总胜利");//赔率名称（中文）
        plLxMap1.put("ldj_matchName","Winner");//雷电竞名称
        plLxMap1.put("ldj_order","final");//雷电竞场次
        plLxMap1.put("yb_matchName","SeriesWin");////亚博名称
        plLxMap1.put("yb_order","0");//亚博场次
        //第一局胜利
        Map plLxMap2 = new HashMap();
        plLxMap2.put("matchType","Winner_r1");
        plLxMap2.put("matchType_ch","第一局胜利");//赔率名称（中文）
        plLxMap2.put("ldj_matchName","Winner");
        plLxMap2.put("ldj_order","r1");
        plLxMap2.put("yb_matchName","GameWin");
        plLxMap2.put("yb_order","1");
        //第二局胜利
        Map plLxMap3 = new HashMap();
        plLxMap3.put("matchType","Winner_r2");
        plLxMap3.put("matchType_ch","第二局胜利");//赔率名称（中文）
        plLxMap3.put("ldj_matchName","Winner");
        plLxMap3.put("ldj_order","r2");
        plLxMap3.put("yb_matchName","GameWin");
        plLxMap3.put("yb_order","2");
        //第一局五杀
        Map plLxMap4 = new HashMap();
        plLxMap4.put("matchType","5Kills_r1");
        plLxMap4.put("matchType_ch","第一局五杀");//赔率名称（中文）
        plLxMap4.put("ldj_matchName","First Team to Get 5 Kills");
        plLxMap4.put("ldj_order","r1");
        plLxMap4.put("yb_matchName","F5K");
        plLxMap4.put("yb_order","1");
        //第二局五杀
        Map plLxMap5 = new HashMap();
        plLxMap5.put("matchType","5Kills_r2");
        plLxMap5.put("matchType_ch","第二局五杀");//赔率名称（中文）
        plLxMap5.put("ldj_matchName","First Team to Get 5 Kills");
        plLxMap5.put("ldj_order","r2");
        plLxMap5.put("yb_matchName","F5K");
        plLxMap5.put("yb_order","2");
        //第一局10杀
        Map plLxMap6 = new HashMap();
        plLxMap6.put("matchType","10Kills_r1");
        plLxMap6.put("matchType_ch","第一局十杀");//赔率名称（中文）
        plLxMap6.put("ldj_matchName","First Team to Get 10 Kills");
        plLxMap6.put("ldj_order","r1");
        plLxMap6.put("yb_matchName","F10K");
        plLxMap6.put("yb_order","1");
        //第二局10杀
        Map plLxMap7 = new HashMap();
        plLxMap7.put("matchType","10Kills_r2");
        plLxMap7.put("matchType_ch","第二局十杀");//赔率名称（中文）
        plLxMap7.put("ldj_matchName","First Team to Get 10 Kills");
        plLxMap7.put("ldj_order","r2");
        plLxMap7.put("yb_matchName","F10K");
        plLxMap7.put("yb_order","2");
        //第一局第一条小龙
        Map plLxMap8 = new HashMap();
        plLxMap8.put("matchType","First_Dragon_r1");
        plLxMap8.put("matchType_ch","第一局击杀第一条小龙");//赔率名称（中文）
        plLxMap8.put("ldj_matchName","Slain the First Dragon");
        plLxMap8.put("ldj_order","r1");
        plLxMap8.put("yb_matchName","FD");
        plLxMap8.put("yb_order","1");
        //第一局第一条大龙
        Map plLxMap9 = new HashMap();
        plLxMap9.put("matchType","First_Baron_r1");
        plLxMap9.put("matchType_ch","第一局击杀第一条大龙");//赔率名称（中文）
        plLxMap9.put("ldj_matchName","Slain the First Baron");
        plLxMap9.put("ldj_order","r1");
        plLxMap9.put("yb_matchName","FirstBaron");
        plLxMap9.put("yb_order","1");
        //第二局第一条小龙
        Map plLxMap10 = new HashMap();
        plLxMap10.put("matchType","First_Dragon_r2");
        plLxMap10.put("matchType_ch","第二局击杀第一条小龙");//赔率名称（中文）
        plLxMap10.put("ldj_matchName","Slain the First Dragon");
        plLxMap10.put("ldj_order","r2");
        plLxMap10.put("yb_matchName","FD");
        plLxMap10.put("yb_order","2");
        //第二局第一条大龙
        Map plLxMap11 = new HashMap();
        plLxMap11.put("matchType","First_Baron_r2");
        plLxMap11.put("matchType_ch","第二局击杀第一条大龙");//赔率名称（中文）
        plLxMap11.put("ldj_matchName","Slain the First Baron");
        plLxMap11.put("ldj_order","r2");
        plLxMap11.put("yb_matchName","FirstBaron");
        plLxMap11.put("yb_order","2");
        //第一局首杀
        Map plLxMap12 = new HashMap();
        plLxMap12.put("matchType","First_Blood_r1");
        plLxMap12.put("matchType_ch","第一局获得一血");//赔率名称（中文）
        plLxMap12.put("ldj_matchName","Draw First Blood");
        plLxMap12.put("ldj_order","r1");
        plLxMap12.put("yb_matchName","FB");
        plLxMap12.put("yb_order","1");
        //第一局首杀
        Map plLxMap13 = new HashMap();
        plLxMap13.put("matchType","First_Blood_r2");
        plLxMap13.put("matchType_ch","第二局获得一血");//赔率名称（中文）
        plLxMap13.put("ldj_matchName","Draw First Blood");
        plLxMap13.put("ldj_order","r2");
        plLxMap13.put("yb_matchName","FB");
        plLxMap13.put("yb_order","2");
        //赔率类型集合
        List<Map> plTypeList = new ArrayList<>();
        plTypeList.add(plLxMap1);
        plTypeList.add(plLxMap2);
        plTypeList.add(plLxMap3);
        plTypeList.add(plLxMap4);
        plTypeList.add(plLxMap5);
        plTypeList.add(plLxMap6);
        plTypeList.add(plLxMap7);
        plTypeList.add(plLxMap8);
        plTypeList.add(plLxMap9);
        plTypeList.add(plLxMap10);
        plTypeList.add(plLxMap11);
        plTypeList.add(plLxMap12);
        plTypeList.add(plLxMap13);
        //设置所有要采集的赔率类型
//        plLxList=plTypeList;
//        return plLxList;
        return null;
    }
    static Map<String,String> ldj_name_id = null;
    static Map<String,String> lh_name_id = null;
    static Map<String,String> yb_name_id = null;
    public void getAllMatch() {
        IPlTeamService plTeamService = (IPlTeamService) ApplicationContextUtil.getBean("plTeamServiceImpl");
        plTeams = plTeamService.selectLhList("1");
        Map<String,String> ldj_name_id_temp = new HashMap<>();
        Map<String,String> lh_name_id_temp = new HashMap<>();
        Map<String,String> yb_name_id_temp = new HashMap<>();
        for (PlTeam plTeam:plTeams) {
            ldj_name_id_temp.put(plTeam.getTeamName(),plTeam.getId().toString());
            lh_name_id_temp.put(plTeam.getTeamLhName(),plTeam.getId().toString());
            yb_name_id_temp.put(plTeam.getTeamSortName(),plTeam.getId().toString());
        }
        ldj_name_id = ldj_name_id_temp;
        lh_name_id = lh_name_id_temp;
        yb_name_id = yb_name_id_temp;
        //获取时间设置
        //暂时只获取今天和明天
        String today = DateUtils.getDate();
        String tomorrow = DateUtils.getNextDay(new Date());
        List<String> dateList = new ArrayList<>();
        dateList.add(today);
        dateList.add(tomorrow);
        //获取雷火比赛
        lh_allMatch = get_lh_allMatch("英雄联盟",dateList);
        //雷电竞获取所有比赛,无游戏id
        ldj_allMatch = get_l_allMatch("英雄联盟",dateList);
        //亚博获取所有比赛
        yb_allMatch = get_yb_allMatch("英雄联盟",dateList);
        //所有比赛包装为Map(队伍id:队伍id,比赛id)
        Map<String,String> lh_map = new HashMap<>();
        Map<String,String> yb_map = new HashMap<>();
        Map<String,String> ldj_map = new HashMap<>();
        matchMesCase(lh_map, yb_map, ldj_map);
        //组装比赛对应
        //雷电竞与亚博
        yb_ldj_code = getSameMatchCode(yb_map, ldj_map,"yb","ldj");
        //亚博与雷火
        yb_lh_code = getSameMatchCode(yb_map, lh_map,"yb","lh");
        //雷电竞与雷火
        ldj_lh_code = getSameMatchCode(ldj_map, lh_map,"ldj","lh");
        //队伍更新
        setTeam();


    }
    /**
     * 比对不同网站已经封装过的信息，找出相同的比赛
     * @param hostA_map
     * @param hostB_map
     * @param hostA_name
     * @param hostB_name
     * @return
     */
    public List<Map<String,String>> getSameMatchCode(Map<String, String> hostA_map, Map<String, String> hostB_map,String hostA_name,String hostB_name) {
        List<Map<String,String>> host_code = new ArrayList<>();
        for (String hostA:hostA_map.keySet()) {
            for (String hostB:hostB_map.keySet()) {
                String[] hostB_split = hostB.split(":");
                if(hostA.equals(hostB_split[0]+":"+hostB_split[1])||hostA.equals(hostB_split[1]+":"+hostB_split[0])){
                    Map<String,String> m = new HashMap<>();
                    m.put(hostA_name+"_code",hostA_map.get(hostA));
                    m.put(hostB_name+"_code",hostB_map.get(hostB));
                    host_code.add(m);
                }
            }
        }
        return host_code;
    }
    //所有比赛包装为Map(队伍id:队伍id,比赛id)

    public void matchMesCase(Map<String, String> lh_map, Map<String, String> yb_map, Map<String, String> ldj_map) {
        //雷火包装
        for (Object lh:lh_allMatch) {
            JSONObject lh_json = JSONObject.parseObject(lh.toString());
            Long home_id = getTeamId("lh", lh_json.getJSONObject("home").getString("team_name"));
            if(home_id==null){
                continue;
            }
            Long away_id = getTeamId("lh", lh_json.getJSONObject("away").getString("team_name"));
            if(away_id==null){
                continue;
            }
            lh_map.put(home_id+":"+away_id,lh_json.getString("event_id"));
        }
        //雷电竞包装

        for (Object ldj:ldj_allMatch) {
            JSONObject ldj_json = JSONObject.parseObject(ldj.toString());
            String home_name = JSONObject.parseObject(ldj_json.getJSONArray("team").get(0).toString()).getString("team_short_name");
            String away_name = JSONObject.parseObject(ldj_json.getJSONArray("team").get(1).toString()).getString("team_short_name");
            Long home_id = getTeamId("ldj", home_name);
            if(home_id==null){
                continue;
            }
            Long away_id = getTeamId("ldj", away_name);
            if(away_id==null){
                continue;
            }
            ldj_map.put(home_id+":"+away_id,ldj_json.getString("id"));
        }
        //亚博包装
        for (Object yb:yb_allMatch) {
            JSONObject yb_json = JSONObject.parseObject(yb.toString());
            //亚博队伍组装
            String home_name = yb_json.getString("PHTName");
            String away_name = yb_json.getString("PATName");
            Long home_id = getTeamId("yb", home_name);
            if(home_id==null){
                continue;
            }
            Long away_id = getTeamId("yb", away_name);
            if(away_id==null){
                continue;
            }
            yb_map.put(home_id+":"+away_id,yb_json.getString("PMatchNo"));
        }
    }

    /**
     * 获取队伍id
     * @param hostName
     * @param name
     * @return
     */
    public Long getTeamId(String hostName,String name) {
        for (PlTeam plTeam:plTeams) {
            if(hostName.equals("ldj")&&name.equals(plTeam.getTeamName())){
               return plTeam.getId();
            }else if(hostName.equals("yb")&&name.equals(plTeam.getTeamSortName())){
                return plTeam.getId();
            }else if(hostName.equals("lh")&&name.equals(plTeam.getTeamLhName())){
                return plTeam.getId();
            }
        }
        return null;
    }
    public void setTeam(){
        IPlTeamService plTeamService = (IPlTeamService) ApplicationContextUtil.getBean("plTeamServiceImpl");
        //雷电竞
        for (Object o:ldj_allMatch) {
            JSONObject json = JSONObject.parseObject(o.toString());
            JSONArray team = json.getJSONArray("team");
//            Map<String, String> l_teamMap = new HashMap<>();
            //雷电竞队伍信息存储（以yb为主）
            for (Object team_l : team) {
                JSONObject team_json = JSONObject.parseObject(team_l.toString());
                PlTeam plTeam = new PlTeam();
                String team_short_name = team_json.getString("team_short_name").trim();
                plTeam.setTeamName(team_short_name);
                List<PlTeam> plTeams = plTeamService.selectPlTeamList(plTeam);
                if(plTeams.size()==0){
                    plTeam.setLdjId(team_json.getString("team_id").trim());
                    plTeamService.insertPlTeam(plTeam);
                }
            }
        }
        //亚博
        for (Object o:yb_allMatch) {
            JSONObject json = JSONObject.parseObject(o.toString());
            //PHTName
            PlTeam plTeam = new PlTeam();
            String PHTName = json.getString("PHTName").trim();
            plTeam.setTeamSortName(PHTName);
            List<PlTeam> plTeams = plTeamService.selectPlTeamList(plTeam);
            if(plTeams.size()==0){
                PlTeam plTeam_new = new PlTeam();
                plTeam_new.setYbId(json.getString("PHTId").trim());
                plTeam_new.setTeamSortName(PHTName);
                plTeamService.insertPlTeam(plTeam_new);
            }
            //PATName
            PlTeam plTeam2 = new PlTeam();
            String PATName = json.getString("PATName").trim();
            plTeam2.setTeamSortName(PATName);
            List<PlTeam> plTeams2 = plTeamService.selectPlTeamList(plTeam2);
            if(plTeams2.size()==0){
                PlTeam plTeam_new = new PlTeam();
                plTeam_new.setYbId(json.getString("PATId").trim());
                plTeam_new.setTeamSortName(PATName);
                plTeamService.insertPlTeam(plTeam_new);
            }
        }
        //雷火
        for (Object o:lh_allMatch) {
            JSONObject json = JSONObject.parseObject(o.toString());
            JSONObject home = json.getJSONObject("home");
            JSONObject away = json.getJSONObject("away");
            PlTeam plTeam = new PlTeam();
            String homeName = home.getString("team_name").trim();
            plTeam.setTeamLhName(homeName);
            List<PlTeam> homes = plTeamService.selectPlTeamList(plTeam);
            if(homes.size()==0){
                plTeam.setLhId(home.getString("team_id").trim());
                plTeamService.insertPlTeam(plTeam);
            }
            //away
            PlTeam plTeam2 = new PlTeam();
            String awayName = away.getString("team_name").trim();
            plTeam2.setTeamLhName(awayName);
            List<PlTeam> aways = plTeamService.selectPlTeamList(plTeam2);
            if(aways.size()==0){
                plTeam2.setLhId(away.getString("team_id").trim());
                plTeamService.insertPlTeam(plTeam2);
            }
        }
        //数据库队伍去重
        //取出亚博不为空雷电竞为空的队伍
        List<PlTeam> yb_ldj = plTeamService.selectTeamByType("yb_ldj");
        //取出雷电竞不为空亚博为空的队伍
        List<PlTeam> ldj_yb = plTeamService.selectTeamByType("ldj_yb");
        //双层循环找出名字一样的
        for (PlTeam yb :yb_ldj) {
            for (PlTeam ldj :ldj_yb) {
                //名字一样的删除雷电竞数据，补全亚博数据
                if(yb.getTeamSortName().toLowerCase().replace(" ", "")
                        .equals(ldj.getTeamName().toLowerCase().replace(" ", ""))){
                    plTeamService.deletePlTeamById(ldj.getId());
                    yb.setTeamName(ldj.getTeamName());
                    yb.setLdjId(ldj.getLdjId());
                    plTeamService.updatePlTeam(yb);
                }
            }
        }
        //取出亚博不为空雷火为空的队伍
        List<PlTeam> yb_lh = plTeamService.selectTeamByType("yb_lh");
        //取出雷火不为空亚博为空的队伍
        List<PlTeam> lh_yb = plTeamService.selectTeamByType("lh_yb");
        //双层循环找出名字一样的
        for (PlTeam yb :yb_lh) {
            for (PlTeam lh :lh_yb) {
                //名字一样的删除雷火数据，补全亚博数据
                if(yb.getTeamSortName().toLowerCase().replace(" ", "")
                        .equals(lh.getTeamLhName().toLowerCase().replace(" ", ""))){
                    plTeamService.deletePlTeamById(lh.getId());
                    yb.setTeamLhName(lh.getTeamLhName());
                    yb.setLhId(lh.getLhId());
                    plTeamService.updatePlTeam(yb);
                }
            }
        }
    }
    //数据转换成 赔率类型名称 ：（队伍：赔率）
    public Map<String,Map> ldj_contentCase(String ldj_code){
        //获取雷电竞中result结构
        JSONObject l_result = ldj_match_contents.get(ldj_code);
        //雷电竞总胜
        JSONArray odds = l_result.getJSONArray("odds");
        JSONArray team = l_result.getJSONArray("team");
        Map<String, String> l_teamMap = new HashMap<>();
        //雷电竞队伍组装
        for (Object team_l : team) {
            JSONObject team_l_object = JSONObject.parseObject(team_l.toString());
            String id = ldj_name_id.get(team_l_object.getString("team_short_name"));
            l_teamMap.put(team_l_object.getString("team_name"), id);
        }
        //雷电竞数据处理
        //数据处理完成后的集合 自赔率类型：（队伍：赔率）
        Map<String,Map> host_match_type = new HashMap<>();
        for (Object odd_l : odds) {
            JSONObject oddJsonObject = JSONObject.parseObject(odd_l.toString());
            for (PlMatchType plMap : plMatchTypes) {
                setMatchType(host_match_type, l_teamMap, oddJsonObject,  plMap.getLdjMatchName(), plMap.getLdjOrder(),"ldj_"+plMap.getMatchType());
            }
        }
        return host_match_type;
    }
    //数据转换成 赔率类型名称 ：（队伍：赔率）
    public Map<String,Map> yb_contentCase(String yb_code){
        //获取亚博parentMatch结构
        JSONObject parentMatch = yb_match_contents.get(yb_code);
        Map<String, String> yb_teamMap = new HashMap<>();
        //亚博队伍组装
        yb_teamMap.put("1",yb_name_id.get(parentMatch.getString("PHTName")));
        yb_teamMap.put("2",yb_name_id.get(parentMatch.getString("PATName")));
        //亚博数据处理
        //数据处理完成后的集合 自赔率类型：（队伍：赔率）
        Map<String,Map> host_match_type = new HashMap<>();
        JSONArray MatchArray = parentMatch.getJSONArray("Match");
        for (Object matchObject : MatchArray) {
            JSONObject matchJsonObject = JSONObject.parseObject(matchObject.toString());
            for (PlMatchType plMap : plMatchTypes) {
                yb_getMatchMap(host_match_type,yb_teamMap, matchJsonObject,"yb_"+plMap.getMatchType(), plMap.getYbMatchName(), plMap.getYbOrder());
            }

        }
        return host_match_type;
    }
    public Map<String,Map<String,String>> lh_contentCase(String lh_code) {
        //获取雷火markets结构
        JSONObject lh_result = lh_match_contents.get(lh_code);
        JSONArray markets = lh_result.getJSONArray("markets");
        Map<String,Map<String,String>> match_type = new HashMap<>();
        //处理赔率为 赔率名称（名称_类型_第几局）：Map(队伍，赔率)
        for (Object market:markets) {
            JSONObject market_json = JSON.parseObject(market.toString());
//            String typeName = market_json.getString("bet_type_name")+"_"+market_json.getString("market_option")+"_"+market_json.getString("map_num");
            String typeName = market_json.getString("market_name").replace(" ", "");
            for (PlMatchType plMap : plMatchTypes) {
                if(plMap.getLhMatchName().replace(" ", "").equals(typeName)){
                    typeName = "lh_"+plMap.getMatchType();
                    break;
                }
            }
            JSONArray selectionArr = market_json.getJSONArray("selection");
            //取出主队和客队
            JSONObject home_team = JSONObject.parseObject(selectionArr.get(0).toString());
            JSONObject away_team = JSONObject.parseObject(selectionArr.get(1).toString());
            Map<String,String> team_odd = new HashMap<>();
            team_odd.put(lh_name_id.get(home_team.getString("bet_type_selection_name")),home_team.getString("euro_odds"));
            team_odd.put(lh_name_id.get(away_team.getString("bet_type_selection_name")),away_team.getString("euro_odds"));
            match_type.put(typeName,team_odd);
        }
        return match_type;

    }
    /**
     * 查询动态页面数据功能列表
     */
//    @RequiresPermissions("webContent:content:list")
    @GetMapping("/getpl")
    @ResponseBody
    public void getpl() throws Exception{
        List<PlCalculateResult> all_result = new ArrayList<>();
        for (Map<String,String> map : yb_ldj_code) {
            PlCalculateResult ldj_yb_plCalRes = new PlCalculateResult();
            ldj_yb_plCalRes.setHostA("雷电竞");
            ldj_yb_plCalRes.setHostB("亚博");
            ldj_yb_plCalRes.setHostACode(map.get("ldj_code"));
            ldj_yb_plCalRes.setHostBCode(map.get("yb_code"));
            try {
                ldj_yb_plCalRes.setStartDate(ldj_match_contents.get(map.get("ldj_code")).getString("start_time"));
                ldj_yb_plCalRes.setHostAView(ldj_match_contents.get(map.get("ldj_code")).getString("match_name"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            JSONObject yb = yb_match_contents.get(map.get("yb_code"));
            ldj_yb_plCalRes.setHostBView(yb.getString("PHTName")+"-vs-"+yb.getString("PATName"));
            //数据处理完成后的集合 自赔率类型：（队伍：赔率）
            Map<String,Map> host_match_type = new HashMap<>();
            host_match_type.putAll(ldj_contentCase(map.get("ldj_code")));
            host_match_type.putAll(yb_contentCase(map.get("yb_code")));
            List<PlCalculateResult> ldj_yb= calculate(host_match_type,"ldj","yb",ldj_yb_plCalRes);
            all_result.addAll(ldj_yb);
        }
        for (Map<String,String> map : ldj_lh_code) {
            PlCalculateResult ldj_lh_plCalRes = new PlCalculateResult();
            ldj_lh_plCalRes.setHostA("雷电竞");
            ldj_lh_plCalRes.setHostB("雷火");
            ldj_lh_plCalRes.setHostACode(map.get("ldj_code"));
            ldj_lh_plCalRes.setHostBCode(map.get("lh_code"));
            ldj_lh_plCalRes.setStartDate(ldj_match_contents.get(map.get("ldj_code")).getString("start_time"));
            ldj_lh_plCalRes.setHostAView(ldj_match_contents.get(map.get("ldj_code")).getString("match_name"));
            JSONObject lh = lh_match_contents.get(map.get("lh_code"));
            ldj_lh_plCalRes.setHostBView(lh.getJSONObject("home").getString("team_name")+"-vs-"+lh.getJSONObject("away").getString("team_name"));
            //数据处理完成后的集合 自赔率类型：（队伍：赔率）
            Map<String,Map> host_match_type = new HashMap<>();
            host_match_type.putAll(ldj_contentCase(map.get("ldj_code")));
            host_match_type.putAll(lh_contentCase(map.get("lh_code")));
            List<PlCalculateResult> ldj_lh= calculate(host_match_type,"ldj","lh",ldj_lh_plCalRes);
            all_result.addAll(ldj_lh);
        }
        for (Map<String,String> map : yb_lh_code) {
            PlCalculateResult yb_lh_plCalRes = new PlCalculateResult();
            yb_lh_plCalRes.setHostA("亚博");
            yb_lh_plCalRes.setHostB("雷火");
            yb_lh_plCalRes.setHostACode(map.get("yb_code"));
            yb_lh_plCalRes.setHostBCode(map.get("lh_code"));
            yb_lh_plCalRes.setStartDate(lh_match_contents.get(map.get("lh_code")).getString("start_datetime"));
            JSONObject yb = yb_match_contents.get(map.get("yb_code"));
            yb_lh_plCalRes.setHostAView(yb.getString("PHTName")+"-vs-"+yb.getString("PATName"));
            JSONObject lh = lh_match_contents.get(map.get("lh_code"));
            yb_lh_plCalRes.setHostBView(lh.getJSONObject("home").getString("team_name")+"-vs-"+lh.getJSONObject("away").getString("team_name"));
            //数据处理完成后的集合 自赔率类型：（队伍：赔率）
            Map<String,Map> host_match_type = new HashMap<>();
            host_match_type.putAll(yb_contentCase(map.get("yb_code")));
            host_match_type.putAll(lh_contentCase(map.get("lh_code")));
            List<PlCalculateResult> yb_lh= calculate(host_match_type,"yb","lh",yb_lh_plCalRes);
            all_result.addAll(yb_lh);
        }
        IPlCalculateResultService iPlCalculateResultService = (IPlCalculateResultService) ApplicationContextUtil.getBean("plCalculateResultServiceImpl");
//        iPlCalculateResultService.insertPlCalculateResultList(all_result);
        /*String refush = "<script type=\"text/javascript\">" +
                " //页面定时刷新.2017.09.27\n" +
                "         window.onload=function () {\n" +
                "             self.setInterval(function () {\n" +

                "                  + window.location.reload();" +
                "             }, 600000);\n" +
                "         }</script>";*/

    }

    /**
     * 计算是否有利润
     * @param host_match_type
     * @return
     */
    public List<PlCalculateResult> calculate(Map<String, Map> host_match_type,String hostA,String hostB,PlCalculateResult base) {
        List<PlCalculateResult> res_list = new ArrayList<>();
        //公式计算是否有利润
        for (PlMatchType plMap : plMatchTypes) {
            String matchType = plMap.getMatchType();
            Map<String,String> hostA_oddsMap = host_match_type.get(hostA+"_"+matchType);
            Map<String,String> hostB_oddsMap = host_match_type.get(hostB+"_"+matchType);
            if(hostA_oddsMap!=null&&hostB_oddsMap!=null){
                for (String key_A : hostA_oddsMap.keySet()) {
                    for (String key_B : hostB_oddsMap.keySet()) {
                        if (!key_A.equalsIgnoreCase(key_B)) {
                            double odd_hostA = Double.parseDouble(hostA_oddsMap.get(key_A).trim());
                            double odd_hostb = Double.parseDouble(hostB_oddsMap.get(key_B).trim());
                            double muthRes = (odd_hostA - 1) * odd_hostb - odd_hostA;
                            muthRes=Math.floor(muthRes*100);
                            PlCalculateResult res = new PlCalculateResult();
                            BeanUtils.copyProperties(base,res);
                            res.setPlType(plMap.getMatchTypeCh());
                            res.setHostAPl(odd_hostA+"");
                            res.setHostBPl(odd_hostb+"");
                            res.setRes((long)muthRes);
                            res_list.add(res);
                        }
                    }
                }
            }
        }
        return res_list;
    }

    /**
     *
     * @param host_match_type 赔率类型：（队伍名称：赔率）
     * @param l_teamMap  队伍简称 ：队伍全称
     * @param oddJsonObject
     * @param group_short_name
     * @param match_stage 比赛场次 （final:最终，r1:第一场）
     * @param l_matchType_name 赔率类型名称
     */
    public void setMatchType(Map<String, Map> host_match_type, Map<String, String> l_teamMap,
                          JSONObject oddJsonObject,String group_short_name , String match_stage, String l_matchType_name) {
        String oddName_l = oddJsonObject.get("name").toString();
        String odd = oddJsonObject.get("odds").toString();
        if (oddJsonObject.get("group_short_name").equals(group_short_name) && oddJsonObject.get("match_stage").equals(match_stage)) {
            Map<String, String> l_match_odds = host_match_type.get(l_matchType_name);
            if (l_match_odds == null) {
                l_match_odds = new HashMap<>();
            }
            l_match_odds.put(l_teamMap.get(oddName_l), odd);
            host_match_type.put(l_matchType_name, l_match_odds);
        }
    }

    /**
     *
     * @param host_match_type  赔率类型：（队伍名称：赔率）
     * @param yb_teamMap 队伍code ：队伍全称
     * @param matchJsonObject
     * @param yb_matchType_name 赔率类型名称
     * @param winName 赔率名称
     * @param GameOrder 场次
     */
    public void yb_getMatchMap(Map<String, Map> host_match_type,Map<String, String> yb_teamMap,  JSONObject matchJsonObject,String yb_matchType_name, String winName, String GameOrder) {
        if (matchJsonObject.getString("GTCode").equals(winName) && matchJsonObject.getString("GameOrder").equals(GameOrder)) {
            Object odds1 = matchJsonObject.getJSONArray("Odds").get(0);
            JSONArray selArray = JSONObject.parseObject(odds1.toString()).getJSONArray("SEL");
            Map<String, String> yb_teamOddMap = host_match_type.get(yb_matchType_name);
            if(yb_teamOddMap==null){
                yb_teamOddMap = new HashMap<>();
            }
            for (Object sel : selArray) {
                JSONObject selJsonObject = JSONObject.parseObject(sel.toString());
                yb_teamOddMap.put(yb_teamMap.get(selJsonObject.get("SCode").toString()), selJsonObject.get("Odds").toString());
            }
            host_match_type.put(yb_matchType_name,yb_teamOddMap);
        }
    }

    /**
     * 从亚博接口的数据格式中获取parentMatch(即需要信息主体)
     *
     * @param y_str
     * @return
     */
    public JSONArray getYbParentMatch(String y_str) {
        JSONObject y_json = JSONObject.parseObject(y_str);
        Object y_report = null;
        try{
            y_report  = y_json.getJSONArray("Sport").get(0);
        }catch (Exception e){
            e.printStackTrace();
        }

        JSONArray lg = JSONObject.parseObject(y_report.toString()).getJSONArray("LG");
        JSONArray y_result = new JSONArray();
//        List y_result = new ArrayList();
        for (Object lg_date : lg) {
            JSONObject lg_jsonObject = JSONObject.parseObject(lg_date.toString());
            y_result.addAll(lg_jsonObject.getJSONArray("ParentMatch"));
        }
        return y_result;
    }

    /*
      // 更新比赛匹配list
     */
    public List<Map> getMctchCode() {
        if (lastrefshTime + refshTime * 1000 > System.currentTimeMillis()) {
            return this.matchCode;
        }
        //获取时间设置
        //暂时只获取今天和明天
        String today = DateUtils.getDate();
        String tomorrow = DateUtils.getNextDay(new Date());
        List<String> dateList = new ArrayList<>();
        dateList.add(today);
        dateList.add(tomorrow);
        //雷电竞获取所有比赛
        JSONArray l_result = get_l_allMatch("英雄联盟",dateList);
        //亚博获取所有比赛
        List y_result = get_yb_allMatch("英雄联盟",dateList);

        String quChong = "";
        //详细比赛code集合
        List<Map> matchCode = new ArrayList<>();
        for (Object l_date : l_result) {
            JSONObject l_jsonObject = JSONObject.parseObject(l_date.toString());
            //去重
            if (l_jsonObject.getString("game_name").equals("英雄联盟") && !quChong.contains(l_jsonObject.getString("match_short_name"))) {
                quChong += l_jsonObject.getString("match_short_name");
                //雷电竞
                for (Object y_date : y_result) {
                    JSONObject y_jsonObject = JSONObject.parseObject(y_date.toString());
                    if (l_jsonObject.getString("match_short_name").toLowerCase().replace(" ", "").contains(y_jsonObject.getString("PHTName").toLowerCase().replace(" ", ""))
                            && l_jsonObject.getString("match_short_name").toLowerCase().replace(" ", "").contains(y_jsonObject.getString("PATName").toLowerCase().replace(" ", ""))) {
                        //组装MatchCode
                        Map<String, String> mc = new HashMap();
                        mc.put("l_code", l_jsonObject.getString("id"));
                        mc.put("yb_code", y_jsonObject.getString("PMatchNo"));
                        matchCode.add(mc);
                    }
                }
            }
        }
        lastrefshTime = System.currentTimeMillis();
        this.matchCode = matchCode;
        return matchCode;
    }
    //亚博获取所有比赛
    //网址：https://www.yabo272.com/app/eGaming
    //-99代表所有，45是英雄联盟
    //PHT队伍1，PAT队伍2
    //接口url:https://imes-yabotiyu.tianjiugong.com/api/GetIndexMatch
    public JSONArray get_yb_allMatch(String gameName,List<String> dateList) {
        String game_id = "";
        if(gameName.equals("英雄联盟")){
            game_id="45";
        }
        String y_str = HttpsClientUtil.doPost("https://imes-yabotiyu.tianjiugong.com/api/GetIndexMatch",
                "{\"SportId\":"+game_id+",\"BaseLGIds\":[-99],\"EventMarket\":-99,\"Token\":null,\"Language\":\"chs\",\"BettingChannel\":1}");
        return getYbParentMatch(y_str);
    }
    //雷电竞获取所有比赛
    //网址：https://www.raybet98.com/match/37211889
    //接口url:http://incpgameinfo.esportsworldlink.com/v2/match?page=1&match_type=2
    public JSONArray get_l_allMatch(String gameName,List<String> dateList) {
        JSONArray l_result = new JSONArray();
        for (int match_type = 0; match_type <= 3; match_type++) {
            JSONArray result = new JSONArray();
            int page = 1;
            do {
                String l_str = HttpClient.doGetCloseable("http://incpgameinfo.esportsworldlink.com/v2/match?page=" + page + "&match_type=" + match_type,null);
                JSONObject l_json = JSONObject.parseObject(l_str);
                result = l_json.getJSONArray("result");
                l_result.addAll(result);
                page++;
            } while (result.size() == 30);
        }
        if(gameName.equals("英雄联盟")){
            JSONArray l_lol_result = new JSONArray();
            for (Object res:l_result) {
                JSONObject res_json = JSONObject.parseObject(res.toString());
                String startTime = res_json.getString("start_time");
                boolean flag = false;
                for (String date:dateList) {
                    String substring = startTime.substring(0, 10);
                    if(date.equals(substring)){
                        flag = true;
                        break;
                    }
                }
                if(flag&&res_json.getString("game_id").equals("70")){
                    l_lol_result.add(res);
                }
            }
            return l_lol_result;
        }
        return l_result;
    }

    /**
     * 获取雷火所有比赛
     * @return
     * 接口地址 https://api-v4.zly889.com/api/v4/events/paginate?game_id=3&date=2020-07-12&sort_by_popular=false&timezone=Asia%2FShanghai&combo=false&lang=zh&page=2
     *///网址 https://e8198.com/games/esports.html
    public JSONArray get_lh_allMatch(String gameName,List<String> dateList) {
        String game_id = "";
        if(gameName!=null&&gameName.equals("英雄联盟")){
            game_id = "3";
        }
        /*//暂时只获取今天和明天
        String today = DateUtils.getDate();
        String tomorrow = DateUtils.getNextDay(new Date());
        List<String> dateList = new ArrayList<>();
        dateList.add(today);
        dateList.add(tomorrow);*/
        //设置header token
        Map<String,String> header = new HashMap<>();
        header.put("Authorization",lh_token);
        JSONArray lh_result = new JSONArray();
        for (String date:dateList) {
            int page = 1;
            JSONArray result = new JSONArray();
            do {
                //game = 3 英雄联盟
                String lh_str = HttpClient.doGetCloseable("https://api-v4.zly889.com/api/v4/events/paginate?" +
                        "game_id="+game_id+"&date="+date+"&sort_by_popular=false&timezone=Asia%2FShanghai&combo=false&lang=zh&page="+page ,header);
                JSONObject lh_json = JSONObject.parseObject(lh_str);
                result = lh_json.getJSONArray("results");
                if(StringUtils.isEmpty(result)){
                    System.out.println("雷火比赛列表数据获取失败,gameName:"+gameName);
                    break;
                }
                lh_result.addAll(result);
                page++;
            } while (result.size() == 20);
        }
        return lh_result;
    }
    /*
      // 获取雷火的比赛内容详情接口
     */
    public JSONObject get_lh_content(String event_id) {
        String zj = "&market_option=MATCH&";
        String j_1 = "&market_option=map&map_option=MAP%201&";
        String j_2 = "&market_option=map&map_option=MAP%202&";
        String j_3 = "&market_option=map&map_option=MAP%203&";
        List<String> j_list = new ArrayList<>();
        j_list.add(zj);
        j_list.add(j_1);
        j_list.add(j_2);
        j_list.add(j_3);
        //设置header token
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", lh_token);
        //收集所有局的赔率
        JSONObject lh_result = new JSONObject();
        JSONArray markets = new JSONArray();
        for (String l_n : j_list) {
            try {
                String l_str = HttpClient.doGetCloseable("https://api-v4.zly889.com/api/v4/events/paginate?" +
                        "event_id=" + event_id + l_n +
                        "timezone=Asia%2FShanghai&combo=false&lang=zh&sort_by_popular=false", header);
                JSONArray results = JSONObject.parseObject(l_str).getJSONArray("results");
                if(results.size()==0){
                    continue;
                }
                lh_result = JSONObject.parseObject(results.get(0).toString());
                JSONArray lh_array = lh_result.getJSONArray("markets");
                markets.addAll(lh_array);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        lh_result.put("markets", markets);
        return lh_result;
    }

    /*
      // 获取亚博的比赛内容详情接口
     */
    public JSONObject get_yb_content(String PMatchNo) {
        JSONObject yb = null;
        try {
            String y_str = HttpsClientUtil.doPost("https://imes-yabotiyu.tianjiugong.com/api/GetMatchDetailsByParent",
                    "{PMatchNo: \"" + PMatchNo + "\", Token: null, Language: \"chs\", BettingChannel: 1}");
            yb = JSONObject.parseObject(getYbParentMatch(y_str).get(0).toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return yb;

    }

    /*
      // 获取雷电竞的比赛内容详情接口
     */
    public JSONObject get_ldj_content(String match_id) {
        String l_str = HttpClient.doGetCloseable("https://incpgameinfo.esportsworldlink.com/v2/odds?match_id=" + match_id,null);
        JSONObject l_json = JSONObject.parseObject(l_str).getJSONObject("result");
        return l_json;
    }

    /**
     * 定时任务获取所有比赛详情
     */
    public void getAllContentQuartz(){
        //刷新所有赔率类型
        IPlMatchTypeService matchTypeService = (IPlMatchTypeService) ApplicationContextUtil.getBean("plMatchTypeServiceImpl");
        plMatchTypes = matchTypeService.selectPlMatchTypeList(new PlMatchType());
        //雷电竞
        Map<String,JSONObject> ldj_contents = new HashMap<>();
        for (Object ldj:ldj_allMatch) {
            JSONObject result = JSONObject.parseObject(ldj.toString());
            String match_id = result.getString("id");
            JSONObject ldj_content= get_ldj_content(match_id);
            ldj_contents.put(match_id,ldj_content);
        }
        ldj_match_contents = ldj_contents;
        //亚博
        Map<String,JSONObject> yb_contents = new HashMap<>();
        for (Object ldj:yb_allMatch) {
            JSONObject result = JSONObject.parseObject(ldj.toString());
            String match_id = result.getString("PMatchNo");
            JSONObject yb_content= get_yb_content(match_id);
            yb_contents.put(match_id,yb_content);
        }
        yb_match_contents = yb_contents;
        //雷火
        Map<String,JSONObject> lh_contents = new HashMap<>();
        for (Object lh:lh_allMatch) {
            JSONObject result = JSONObject.parseObject(lh.toString());
            String match_id = result.getString("event_id");
            JSONObject lh_content= get_lh_content(match_id);
            lh_contents.put(match_id,lh_content);
        }
        lh_match_contents = lh_contents;
        //计算
        try {
            getpl();
        }catch (Exception e){
            e.printStackTrace();
        }
    }










    /**
     * 用于接收MT5源交易信号
     */
    @RequiresPermissions("webContent:content:getPoint")
    @PostMapping("/getPoint")
    @ResponseBody
    public String getPoint(ZhgsWebContent zhgsWebContent) {
        return null;
    }
}
